package com.lry.basic.algorithm.loadbanlance;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 加权轮询
 */
public class WeightRoundRobin {
    private static AtomicInteger ai = new AtomicInteger(0);

    public static Server getServer(){
        int totalWeight = 0;
        for(Server server:WeightServer.servers){
            totalWeight +=server.getWeight();
        }
        int pos = ai.getAndIncrement() % totalWeight;

        for(Server server:WeightServer.servers){
            if(pos<server.getWeight()){
                return server;
            }
            pos-=server.getWeight();
        }
        return null;
    }

    public static void main(String[] args) {
        for(int i=0;i<30;i++){
            Server server = getServer();
            server.setCallNum(server.getCallNum()+1);
            System.out.println(server);
        }
        System.out.println("-------------------------------------------------------");

        for(Server server:WeightServer.servers){
            System.out.println(server);
        }
    }

}
